package com.xinghai.security.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

/**
 * @Author SJie

 * @Date 2024/11/15 18:00
 */
@Component
public class IpWhiteListFilter extends OncePerRequestFilter {

    Logger log = Logger.getLogger(IpWhiteListFilter.class.getName());

    // 设置可以访问的ip白名单
    private static final List<String> WHITE_LIST = Arrays.asList("192.168.2.97", "127.0.0.1");

    // 登录sso接口
    private static final String LOGIN_SSO_PATH = "/loginSso";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //log.info("ip==========>"+request.getRemoteAddr());
        // 获取uri
        String requestURI = request.getRequestURI();
        // 判断是否为需要过滤的接口
        if (LOGIN_SSO_PATH.equals(requestURI)) {
            // 获取请求ip
            String clientIp = request.getRemoteAddr();
            // 判断ip是否在白名单中
            if (WHITE_LIST.contains(clientIp)) {
                // IP在白名单中，继续处理请求
                filterChain.doFilter(request, response);
            } else {
                // IP不在白名单中，返回错误响应
                log.info("{"+clientIp+"}尝试访问{"+requestURI+"}");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().write("IP地址不在白名单中");
            }
        } else {
            // 其他路径直接放行
            filterChain.doFilter(request, response);
        }
    }
}
